package com.cyw.common.utils.http;

import com.cyw.common.utils.LogUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;

import java.util.StringJoiner;

public class HttpResponseWrapper {

    /**
     * 发送的请求，消费响应后需要执行abort方法
     * @see HttpRequestBase#abort()
     * @see #abort()
     */
    private HttpRequestBase requestBase;

    /**
     * 执行的结果，执行失败后可能为null
     */
    private HttpResponse httpResponse;

    /**
     * 执行失败时捕获的或转换的异常
     */
    private Exception exception;

    /**
     * 响应实体的缓存
     */
    private String entityAsStringCache;

    public HttpResponseWrapper() {
    }

    public HttpResponseWrapper(HttpResponse httpResponse, Exception exception) {
        this.httpResponse = httpResponse;
        this.exception = exception;
    }

    public HttpResponse getHttpResponse() {
        return httpResponse;
    }

    public void setHttpResponse(HttpResponse httpResponse) {
        this.httpResponse = httpResponse;
    }

    public Exception getException() {
        return exception;
    }

    public void setException(Exception exception) {
        this.exception = exception;
    }

    public HttpRequestBase getRequestBase() {
        return requestBase;
    }

    public void setRequestBase(HttpRequestBase requestBase) {
        this.requestBase = requestBase;
    }

    /**
     * abort an ongoing request
     * This will make sure that the client doesn't have to consume the entire body of the request to release the connection
     */
    public void abort() {
        if (requestBase != null) {
            requestBase.abort();
        }
    }

    /**
     * 需要在<b>abort</b>方法调用之前执行，否则可能会拿不到数据
     * 该方法也会触发<b>abort</b>的执行
     *
     * @return
     * @see #abort()
     */
    public String getEntityAsString() {
        if (entityAsStringCache != null) {
            return entityAsStringCache;
        }

        if (httpResponse == null || httpResponse.getEntity() == null) {
            printException();
            entityAsStringCache = "";
            return entityAsStringCache;
        }
        try {
            entityAsStringCache = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            return entityAsStringCache;
        } catch (Exception e) {
            LogUtils.printWarn(e);
        } finally {
            abort();
        }
        entityAsStringCache = "";
        return entityAsStringCache;
    }

    /**
     * 打印请求过程中的异常
     */
    public void printException() {
        if (exception != null) {
            LogUtils.printError(exception);
        }
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", HttpResponseWrapper.class.getSimpleName() + "[", "]")
                .add("requestBase=" + requestBase)
                .add("httpResponse=" + httpResponse)
                .add("exception=" + exception)
                .toString();
    }
}
